package team.yidong.fenda.wx.Service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.Answer;
import team.yidong.fenda.entity.User;
import team.yidong.fenda.repository.AnswerRepository;
import team.yidong.fenda.repository.PraiseRepository;
import team.yidong.fenda.repository.QuestionRepository;
import team.yidong.fenda.repository.UserRepository;
import team.yidong.fenda.wx.Service.WxPraiseService;

import java.util.Set;

/**
 * Created by xuanlong on 2017/10/15.
 */
@Service
public class WxPraiseServiceImpl implements WxPraiseService {
    @Autowired
    PraiseRepository praiseRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    AnswerRepository answerRepository;
    @Autowired
    QuestionRepository questionRepository;

    @Transactional
    @Override
    public String praise(Integer answerId, String wxNumber) {
        Answer answer = praiseRepository.findPraise(wxNumber, answerId);
        if (answer == null) {
            User user = userRepository.findByUserOpenId(wxNumber);
            Answer answer1 = answerRepository.findOne(answerId);

            Set<User> userSet = answer1.getPraiseUserSet();
            userSet.add(user);
            answer1.setPraiseUserSet(userSet);
            answerRepository.save(answer1);
            return "点赞成功";
        } else {
            return "曾经点赞";
        }
    }
}
